package service

import (
	"context"
	"github.com/go-redis/redis/v8"
	"github.com/gorilla/websocket"
	"gitlab.vrviu.com/inviu/backend-go-public/gopublic/httpwrap"
	"sync"
	"time"
)

const (
	REQ_UTOKEN_SUCC    = 1
	REQ_UTOKEN_ERR     = -1
	APPLY_UTOKEN_SUCC  = 2
	APPLY_UTOKEN_FAIL  = -2
	REQ_APPLY_SUCC     = 3
	REQ_APPLY_ERR      = -3
	APPLY_SUCC         = 4
	ENter_UQ           = 5
	Exit_UQ            = 6
	APPLY_FAIL         = -4
	WS_CONN_SUCC       = 7
	WS_CONN_FAIL       = -7
	LAUNCH_GAME_SENDED = 8
	LAUNCH_GAME_SUCC   = 9
	LAUNCHGAME_FAIL    = -9
	ALLOC_PREPARE      = 10
	AREA_QING          = 11
	ALLOC_SUCC         = 12
	GAMESTART_FAIL     = 13
	LAUNCHFALURE       = 14
	READY_RENDER       = 15
	ForceQuit          = 16
	CURRENT_LIMITING   = -5
	IS_QUEUE           = 17
	NO_QUEUE           = 18
	EXIt_UQ_FORCE      = 19
)

type AreaClientMgr struct {
	AreaClients []*AreaClient
	Result_key  string
}

type ClientController struct {
	IsStreaming    bool   `json:"is_streaming"`
	IsQuickOut     bool   `json:"is_quick_out"`
	IsAutoResist   bool   `json:"is_auto_resist"`
	DelayExit      int    `json:"delay_exit"`
	RsetID         int    `json:"rset_id"`
	IsAutoRegister bool   `json:"is_auto_register"`
	TaskID         string `json:"task_id"`
}
type AreaClient struct {
	Uid              uint64
	AreaType         int
	Atoken           string
	Utoken           string
	DevID            string
	Gid              uint64
	bizType          uint64
	FlowID           string
	AreaAddr         string
	UServoAddr       string
	UAccessAddr      string
	UserID           string
	DevType          int
	WSConn           *websocket.Conn
	HBSigCh          chan bool
	StartTime        time.Time
	HoldTime         int
	ClientExit       bool
	AllocState       bool
	AllocTime        time.Time
	QueueState       bool
	QueueTime        time.Time
	PreAllocTime     time.Time
	status           int
	fail_msg         error
	redisCli         redis.UniversalClient
	Result_key       string
	RelaunchDuration int
	RelaunchTimes    int
	wg               *sync.WaitGroup
	ClientController *ClientController
}

type AreaClientInfo struct {
	Uid         uint64
	bizType     uint64
	AreaType    int
	Atoken      string
	Utoken      string
	DevID       string
	Gid         uint64
	FlowID      string
	AreaAddr    string
	UServoAddr  string
	UAccessAddr string
	UserID      string
	DevType     int
	Status      int
	Fail_msg    string
	Is_done     int
	AllocTime   float64
}

// TokenInfo token信息
type TokenInfo struct {
	Token     string `json:"token"`
	AppUserID string `json:"app_userid"`
	UserID    string `json:"userid"`
	//ExpireTime time.Time `json:"expire_time"`
}

// TokenResult token获取结果
type TokenResult struct {
	Head httpwrap.HTTPCommonHead `json:"ret"`
	Info TokenInfo               `json:"token_info"`
}

// callback 获取结果
type CallbackResult struct {
	Head httpwrap.HTTPCommonHead `json:"ret"`
	Body CallbackBody            `json:"body"`
}

// callback 获取返回信息
type CallbackBody struct {
	TaskID string `json:"task_id"`
}

// AccessInfo 接入信息
type AccessInfo struct {
	AccessAddr string `json:"access_ipv4_address"`
	AccessPort int    `json:"access_ipv4_port"`
}

// QueueInfo -
type QueueInfo struct {
	Addr        string `json:"address"`
	Port        uint16 `json:"port"`
	Rank        int64  `json:"rank"`
	Total       int64  `json:"total"`
	SessionID   string `json:"session_id"`
	Ewtime      int    `json:"ewtime"`
	SegInterval int64  `json:"seg_interval"`
}

// AreaInfo 区域信息
type AreaInfo struct {
	FlowID string     `json:"flow_id"`
	Token  string     `json:"token"`
	UUID   uint64     `json:"uuid"`
	UGID   uint64     `json:"ugid"`
	UID    uint64     `json:"uid"`
	GID    uint64     `json:"gid"`
	Info   AccessInfo `json:"access_info"`
	QInfo  QueueInfo  `json:"queue_info"`
}

// AreaResult 申请区域结果
type AreaResult struct {
	Head httpwrap.HTTPCommonHead `json:"ret"`
	Info AreaInfo                `json:"body"`
}

// UnionRankInfo -
type UnionRankInfo struct {
	RankTs      int64  `json:"rank_ts"`
	Rank        int64  `json:"rank"`
	Total       int64  `json:"total"`
	QueueFlag   int64  `json:"queue_flag"`
	SegInterval int64  `json:"seg_interval"`
	FlowID      string `json:"flow_id"`
	Ewtime      int    `json:"ewtime"`
}

// UnionRankResult -
type UnionRankResult struct {
	Head httpwrap.HTTPCommonHead `json:"ret"`
	Info UnionRankInfo           `json:"body"`
}

var ctx_map = sync.Map{}

type routine_controller struct {
	ctx    context.Context
	cancel context.CancelFunc
}

type StressTestBody struct {
	UserID          string `json:"user_id"`
	Total           uint64 `json:"total"`
	HoldTime        int    `json:"holdtime"`
	TaskID          string `json:"task_id"`
	Biz             uint64 `json:"biz"`
	GID             uint64 `json:"gid"`
	SPConcurrency   uint64 `json:"sp_concurrency"`
	PerformanceMode uint64 `json:"performance_mode"`
	Env             string `json:"env"`
	IsQuickOut      bool   `json:"is_quickout"`
	IsStreaming     bool   `json:"is_streaming"`
	DelayExit       int    `json:"delay_exit"`
	RSetID          int    `json:"rset_id"`
	IsAutoRegister  bool   `json:"is_auto_regist"`
	StartUUID       uint64 `json:"start_uuid"`
	IsDelKey        bool   `json:"is_del_key"`
}

type TaskStartParams struct {
	// 基础任务信息
	UserID       string `json:"user_id"`       // 发起用户唯一标识
	TaskID       string `json:"task_id"`       // 任务唯一标识符
	BusinessType uint64 `json:"business_type"` // 业务类型分类编码
	GroupID      uint64 `json:"group_id"`      // 任务所属资源组/集群ID

	// 资源控制参数
	TotalInstances  uint64 `json:"total_instances"`   // 需要启动的总实例数量
	HoldDurationSec int    `json:"hold_duration_sec"` // 资源保持时间（秒）
	DelayExitSec    int    `json:"delay_exit_sec"`    // 结束延迟等待时间（秒）

	// 性能配置
	MaxConcurrency  uint64 `json:"max_concurrency"`   // 最大并发处理数
	PerformanceMode uint64 `json:"performance_mode"`  // 性能模式选择标记
	ServicePoolSize uint64 `json:"service_pool_size"` // 服务池并发容量

	// 环境控制
	Environment   string `json:"environment"`     // 运行环境标识 (sit/uat/pro)
	ResourceSetID int    `json:"resource_set_id"` // 关联资源集合ID

	// 功能开关
	QuickTermination bool `json:"quick_termination"`  // 是否启用快速终止
	StreamingMode    bool `json:"streaming_mode"`     // 是否启用流式处理模式
	AutoRegistration bool `json:"auto_registration"`  // 是否自动注册资源
	DeleteKeyOnExit  bool `json:"delete_key_on_exit"` // 退出时删除关联密钥

	StartUUID uint64 `json:"start_uuid"` // 启动批次唯一标识
}
